import java.net.MalformedURLException;
import java.rmi.*;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.*;
import java.util.*;


public class Server extends UnicastRemoteObject implements Server_itf{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Map<String, ServerObject> serveurNom = new HashMap<String,ServerObject>();
	private Map<Integer, ServerObject> serveurID = new HashMap<Integer, ServerObject>();
	
	public Server() throws RemoteException {
		super();
		this.serveurNom = new HashMap<String, ServerObject>();
		this.serveurID = new HashMap<Integer, ServerObject>();
	}

	@Override
	public int create(Object o) throws RemoteException {
		int id = serveurID.size();
		serveurID.put(id, new ServerObject(id, o));
		return id;
	}

	@Override
	public Object lock_read(int id, Client_itf client) throws RemoteException {
		if (client != null) {
			//Client.init() pas fait, ou pas de client
			ServerObject servObj = serveurID.get(id);
			if (servObj != null) {
				// l'object n'existe pas (id pas trouvé)
				return servObj.lock_read(client);
			}
		}
		return null;
	}

	@Override
	public Object lock_write(int id, Client_itf client) throws RemoteException {
		if (client != null) {
			//Client.init() pas fait, ou pas de client
			ServerObject servObj = serveurID.get(id);
			if (servObj != null) {
				// l'object n'existe pas (id pas trouvé)
				return servObj.lock_write(client);
			}
		}
	return null;
	}

	@Override
	public synchronized int lookup(String name) throws RemoteException {
		ServerObject servObj = serveurNom.get(name); 
		if (servObj != null) {
			return (servObj.getId());
		}
		return -1;
	}

	@Override
	public void register(String name, int id) throws RemoteException {
		ServerObject servObj = serveurID.get(id);
		if (servObj != null) {
			if (!serveurNom.containsKey(name)) {
				serveurNom.put(name,servObj);				
			}
		}
	}
	
    public static void main(String argv[]) {
    	try {
			LocateRegistry.createRegistry(2011);
			Server_itf serv = new Server();
			Naming.bind("//localhost:2011/Serveur", serv);
			System.out.println("Serveur en marche");
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {	// A DEMANDER
			e.printStackTrace();
		} catch (AlreadyBoundException e) {
			e.printStackTrace();
		}
    }
}
